package com.fileReplace.util;

import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * IO操作的工具类
 * @author larry
 *
 */
public class FileUtils {
	
	/**
	 * 获取替换后的文件集合
	 * @param fileList 文件列表
	 * @param fromString 被替换的字符串
	 * @param toString 要替换成的字符串
	 * @return
	 */
	public boolean doReplacedFile(List<File> fileList,String fromString,String toString,boolean ignoreCase){
		int sCount=0;
		int fCount=0;
		for(File file:fileList){
			try {
				boolean isBeChange=false;
				String charset=getFileCharacterEnding(file);
				Log.info("正在处理："+file.getAbsoluteFile()+"文件，其编码："+charset);
				InputStreamReader isr=new InputStreamReader(new FileInputStream(file),charset);
				File destFile=new File(file.getAbsolutePath()+"`");
				OutputStreamWriter osw =new OutputStreamWriter(new FileOutputStream(destFile),charset);
				BufferedReader br =new BufferedReader(isr);
				String line;
				while((line=br.readLine())!=null){
					if(ignoreCase){
						//忽略大小写
						if(line.contains(fromString)){
							line=line.replace(fromString, toString);
							isBeChange=true;
						}
						osw.write(line+'\n');
					}else{
						//不忽略大小写
						if(line.contentEquals(fromString)){
							line=line.replace(fromString, toString);
							isBeChange=true;
						}
						osw.write(line+'\n');
					}
				}
				osw.flush();
				isr.close();
				br.close();
				osw.close();
				if(!isBeChange){
					//对没有发生状态编码的文件不做任何处理
					destFile.delete();
					Log.info("\t\t\t"+file.getAbsolutePath()+"  文件不含有要替换的字符串");
					fCount++;
				}else{
					file.delete();
					destFile.renameTo(file);
					Log.info(file.getAbsolutePath()+"  文件操作成功");
					sCount++;
				}
			} catch (FileNotFoundException e) {
				Log.error(file.getAbsolutePath()+"错误："+e.getLocalizedMessage());
				fCount++;
				return false;
			} catch (IOException e) {
				Log.error(file.getAbsolutePath()+"错误："+e.getLocalizedMessage());
				fCount++;
				return false;
			}
		}
		Log.info("变更数："+sCount+"失败数:"+fCount);
		return true;
	}
	/**
	 * 获取文件的编码
	 * @param file
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String getFileCharacterEnding(File file){
		CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
		detector.add(JChardetFacade.getInstance());
		Charset charset=null;
		try {
			charset=detector.detectCodepage(file.toURL());
		} catch (MalformedURLException e) {
			Log.info(e.getLocalizedMessage());
		} catch (IOException e) {
			Log.info(e.getLocalizedMessage());
		}
		return charset!=null?charset.name():"UTF-8";
	}
}
